//
//  SelectAddressView.m
//  WatermarkCamera
//
//  Created by zhibao on 2023/9/14.
//

#import "SelectAddressView.h"
#import "SelectAddressCell.h"
#import "LocationModel.h"
@interface SelectAddressView()<UITableViewDelegate,UITableViewDataSource,QMUITextFieldDelegate,AMapSearchDelegate>{
}
@property (nonatomic,strong) MYTableView *showTableView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong) AMapSearchAPI *search;
@end
@implementation SelectAddressView
- (instancetype)init{
    self = [super initWithFrame:CGRectMake(0, MY_Screen_H, MY_Screen_W, MY_Screen_H)];
    if(self){
        self.search = [[AMapSearchAPI alloc] init];
        self.search.delegate = self;
        LocationModel *model = [GetLocation sharedManager].model;
        AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
        request.location = [AMapGeoPoint locationWithLatitude:[model.lat floatValue] longitude:[model.lon floatValue]];
        request.types = @"商务住宅|地名地址信息|汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|公共设施";
        request.sortrule = 0;
        [self.search AMapPOIAroundSearch: request];
        _dataArray = [NSMutableArray new];
        self.backgroundColor = MyColorAlpha(@"000000", 0.0);
        [[UIApplication sharedApplication].delegate.window.rootViewController.view addSubview:self];
        [self initView];
    }
    return self;
}

-(void)initView{
    
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, MY_Screen_H - 473, MY_Screen_W, 64 + 20)];
    topView.layer.cornerRadius = 20;
    topView.backgroundColor = UIColor.whiteColor;
    [self addSubview:topView];
    
    if(topView){
        UILabel *topTitleLabel = [UILabel new];
        topTitleLabel.text = LocalizedString(@"选择地点");
        topTitleLabel.font = MY_SCALE_SemiboldFONT(16);
        topTitleLabel.textColor = MYBlock;
        [topView addSubview:topTitleLabel];
        [topTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(topView);
            make.top.mas_equalTo(16);
        }];
        
        UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [cancelBtn setImage:[UIImage imageNamed:@"com_close_qian"] forState:UIControlStateNormal];
        [topView addSubview:cancelBtn];
        [cancelBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        cancelBtn.tag = 1000;
        [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(15);
            make.right.mas_equalTo(-15);
        }];
    }
    
    UIView *temView = [[UIView alloc]initWithFrame:CGRectMake(0, topView.bottom - 20, MY_Screen_W , 80)];
    temView.backgroundColor = UIColor.whiteColor;
    [self addSubview:temView];
    
    QMUITextField *field = [[QMUITextField alloc]initWithFrame:CGRectMake(17,topView.top + 65, MY_Screen_W - 34, 28)];
    field.backgroundColor = MyColor(@"#ECECEC");
    field.layer.cornerRadius = 13;
    field.placeholder = LocalizedString(@"搜索附近地点");
    field.placeholderColor = MyColor(@"999999");
    field.font = MY_SCALE_RegularFONT(12);
    field.textColor = MYBlock;
    [field.keyboardToolbar.doneBarButton setTarget:self action:@selector(doneAction:)];
    field.returnKeyType = UIReturnKeySearch;
    field.delegate = self;
    field.leftViewMode = UITextFieldViewModeAlways;
    [self addSubview:field];
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(20, 0, 30, 13)];
    UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 0, 13, 13)];
    imgView.image = [UIImage imageNamed:@"h_water_search"];
    [leftView addSubview:imgView];
    imgView.centerX = leftView.width / 2;
    imgView.centerY = leftView.height / 2;
    field.leftView = leftView;
    
    self.showTableView = [[MYTableView alloc]initWithFrame:CGRectMake(0, topView.top + 108, MY_Screen_W, 315) style:UITableViewStylePlain];
    self.showTableView.delegate = self;
    self.showTableView.dataSource = self;
    
    self.showTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self addSubview:self.showTableView];
    self.showTableView.rowHeight = 55;
    self.showTableView.backgroundColor = UIColor.whiteColor;
    self.showTableView.nodataView.backgroundColor = UIColor.whiteColor;
    [self.showTableView setNoDataType:TableViewNoDataType_Search];
    [self.showTableView removeMJRefresh];
    
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, self.showTableView.bottom, MY_Screen_W, 50)];
    bottomView.backgroundColor = UIColor.whiteColor;
    [self addSubview:bottomView];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroundColor = MyColorAlpha(@"000000", 0.4);
        self.top = 0;
    }];
}

/* POI 搜索回调. */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
//    if (response.pois.count == 0)
//    {
//        return;
//    }
    
    [_dataArray removeAllObjects];
    for (AMapPOI *poi in response.pois) {
        DLog(@"obj===%@    %@",poi.name,poi.address);
        [_dataArray addObject:poi];
    }
    [_showTableView reloadData];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    LocationModel *model = [GetLocation sharedManager].model;
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:[model.lat floatValue] longitude:[model.lon floatValue]];
    request.keywords = textField.text;
    request.types = @"商务住宅|地名地址信息|汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|公共设施";
    request.sortrule = 0;
    [self.search AMapPOIAroundSearch: request];
    return YES;
}

-(void)doneAction:(UITextField *)textField{
    LocationModel *model = [GetLocation sharedManager].model;
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:[model.lat floatValue] longitude:[model.lon floatValue]];
    request.keywords = textField.text;
    request.types = @"商务住宅|地名地址信息|汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|公共设施";
    request.sortrule = 0;
    [self.search AMapPOIAroundSearch: request];
}

#pragma mark - tableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AMapPOI *content = self.dataArray[indexPath.row];
    static NSString *identifier = @"SelectAddressCell";
    SelectAddressCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell==nil) {
        cell=[[SelectAddressCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
    [cell update:content];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(_selectpoiBlock){
        _selectpoiBlock(self.dataArray[indexPath.row]);
    }
    [self btnClick:nil];
}

-(void)btnClick:(UIButton *)btn{
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroundColor = MyColorAlpha(@"000000", 0.4);
        self.top = MY_Screen_H;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
   
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // 圆角角度
    CGFloat radius = 10.f;
    // 设置cell 背景色为透明
    cell.backgroundColor = UIColor.whiteColor;
    // 创建两个layer
    CAShapeLayer *normalLayer = [[CAShapeLayer alloc] init];
    CAShapeLayer *selectLayer = [[CAShapeLayer alloc] init];
    // 获取显示区域大小
    CGRect bounds = CGRectInset(cell.bounds, [UIScreen mainScreen].bounds.size.width/375 * 14, 0);
    // cell的backgroundView
    UIView *normalBgView = [[UIView alloc] initWithFrame:bounds];
    // 获取每组行数
    NSInteger rowNum = [tableView numberOfRowsInSection:indexPath.section];
    // 贝塞尔曲线
    UIBezierPath *bezierPath = nil;
    
    if (rowNum == 1) {
        // 一组只有一行（四个角全部为圆角）
        bezierPath = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(radius, radius)];
        normalBgView.clipsToBounds = NO;
    }else {
        normalBgView.clipsToBounds = YES;
        if (indexPath.row == 0) {
            normalBgView.frame = UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(0, 0, 0, 0));
            CGRect rect = UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(0, 0, 0, 0));
            // 每组第一行（添加左上和右上的圆角）
            bezierPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:(UIRectCornerTopLeft|UIRectCornerTopRight) cornerRadii:CGSizeMake(radius, radius)];
        }else if (indexPath.row == rowNum - 1) {
            normalBgView.frame = UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(0, 0, 0, 0));
            CGRect rect = UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(0, 0, 0, 0));
            // 每组最后一行（添加左下和右下的圆角）
            bezierPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:(UIRectCornerBottomLeft|UIRectCornerBottomRight) cornerRadii:CGSizeMake(radius, radius)];
        }else {
            // 每组不是首位的行不设置圆角
            bezierPath = [UIBezierPath bezierPathWithRect:bounds];
        }
    }
    
    // 阴影
    normalLayer.shadowColor = MyColor(@"#F1F1F1").CGColor;
    normalLayer.shadowOpacity = 0.2;
    normalLayer.shadowOffset = CGSizeMake(0, 0);
    normalLayer.path = bezierPath.CGPath;
    normalLayer.shadowPath = bezierPath.CGPath;
    
    // 把已经绘制好的贝塞尔曲线路径赋值给图层，然后图层根据path进行图像渲染render
    normalLayer.path = bezierPath.CGPath;
    selectLayer.path = bezierPath.CGPath;
    
    // 设置填充颜色
    normalLayer.fillColor = MyColor(@"#F1F1F1").CGColor;
    //    if (indexPath.row % 2 == 0) {
    //            normalLayer.fillColor = [UIColor whiteColor].CGColor;
    //        }else{
    //            normalLayer.fillColor = [UIColor colorWithHexString:@"e9e9e9"].CGColor;
    //        }
    // 添加图层到nomarBgView中
    [normalBgView.layer insertSublayer:normalLayer atIndex:0];
    normalBgView.backgroundColor = UIColor.clearColor;
    cell.backgroundView = normalBgView;
}

@end
